<?php

namespace app\models;

use app\librarys\Tools;
use yii\mongodb\ActiveRecord;

/**
 * 商品访问记录.
 * 记过此记录累计后,可以作为商品受关注程度的参考数据
 * @package app\models
 */
class GoodsVisitLog extends ActiveRecord
{
    public static function add($goodsCode, $userId, $institutionCode)
    {
        $log = new GoodsVisitLog();
        $log->_id = Tools::uuid();
        $log->goodsCode = $goodsCode;
        $log->userId = $userId;
        $log->institutionCode = $institutionCode;
        $log->createDatetime = time();
        $log->save();
    }

    public static function getGroupCount()
    {
        $keys = array("goodsCode" => 0);
        $initial = array("count" => 0);
        $reduce = "function (obj, prev) { prev.count++; }";
        $items = self::getCollection()->group($keys, $initial, $reduce);
        return $items;
    }

    public static function getCount()
    {
        return self::find()->count();
    }

    public static function getList($page, $pageSize)
    {
        $items = self::find()->offset($page * $pageSize)
            ->limit($pageSize)
            ->orderBy('createDatetime desc')
            ->asArray()
            ->all();
        return $items;
    }

    public function attributes()
    {
        return [
            '_id',  // pk
            'goodsCode',  // 商品编码
            'userId',  // 访问此商品的用户id
            'institutionCode',  // 访问此商品所属的机构编码
            'createDatetime'
        ];
    }
}